/*
Copyright 2009 - 2013 Peter Krajnc, SCREENWORKER

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.compactmvc.services.remotingservice
{
	import org.compactmvc.services.interfaces.IRemotingService;
	import org.compactmvc.interfaces.IModel;
	import org.compactmvc.patterns.Controller;
	import org.compactmvc.patterns.Model;
	
	import flash.events.AsyncErrorEvent;
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.NetConnection;
	import flash.net.ObjectEncoding;
	import flash.net.Responder;
	
	public class RemotingService extends Model implements IModel, IRemotingService
	{
		public static var NAME:String = 'RemotingService';
		public static const STATUS_TYPE_RESPONDER:String = 'ResponderStatus';
		public static const STATUS_TYPE_NET:String = 'NetStatus';
		
		private var _netConnection:NetConnection;
		private var _responder:Responder;
		private var _gateway:String;

		public function RemotingService(name:String, controller:Controller)
		{
			super(name, controller);
			
			_responder = new Responder(responderResultHandler, responderStatusHandler);
			
			//NET ONNECTION
			NetConnection.defaultObjectEncoding = ObjectEncoding.AMF3;
			_netConnection = new NetConnection();
			_netConnection.client = this;
			_netConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			_netConnection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			_netConnection.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); 
			_netConnection.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);

		}	
		
		public function AppendToGatewayUrl(extra:String):void
		{
		   _netConnection.connect(_netConnection.uri + extra);
	    }
		
		/**
		 * Invokes a command or method 
		 * @param classMethod
		 * @param arguments
		 * @param mockUp add a mockup object here to simulate the result
		 * 
		 */			
		protected function call(classMethod:String, arguments:Object=null, mockUp:Object=null):void
		{
			if(mockUp == null)
			{
     	 		_netConnection.call(classMethod, _responder, arguments ); 
   			}
     	 	else
     	 	{ 	 			
     	 		responderResultHandler(mockUp);
     	 	}
		}
		
		private function responderResultHandler(result:Object):void
		{
			 resultHandler(result);
		}
				
		private function responderStatusHandler(f:Object):void
		{
			statusHandler(STATUS_TYPE_RESPONDER, f);
		}
				
		private function netStatusHandler(e:NetStatusEvent):void
		{
			statusHandler(STATUS_TYPE_NET, e.info);
		}
			
		private function securityErrorHandler(e:SecurityErrorEvent):void
		{
			errorHandler('SECURITY ERROR: ' + e.text);
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			errorHandler('IO ERROR: ' + e.text);
		}
		
		private function asyncErrorHandler(e:AsyncErrorEvent):void
		{
			errorHandler('ASYNC ERROR: ' + e.text);
		}
		
		public function reset():void
		{
			_netConnection.close();
			_netConnection.removeEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			_netConnection.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			_netConnection = null;
			_responder = null;		
		}
		
		public function errorHandler(message:String):void
		{
			//overriden by subClass
		}
		
		public function resultHandler(result:Object):void
		{
			//overriden by subClass
		}
		
		public function statusHandler(statusType:String, statusObject:Object=null):void
		{
			//overriden by subClass
		}
		
		override public function removeHandler():void
		{
			reset();
		}
		
		public function set gateway(value:String):void
		{
			_netConnection.close();
			
			_gateway = value;
			
			try
			{
				_netConnection.connect(value);
			}
			catch(e:Error)
			{
				errorHandler(e.message);
			}
		}
		
		public function get gateway():String
		{
			return _gateway;
		}	
	}
}
